#!/bin/sh -


G_TRACE_SC="/export/home/fred/gopherd.d"
#GOPHERD="dtrace -s ${G_TRACE_SC} -c /export/home/fred/gopherd/gopherd"
GOPHERD="/export/home/fred/gopherd/gopherd"
GOPHERD_FLAGS="-a /export/home/fred/gfw.list -c /export/home/fred/gspace -h 10.0.0.9";
GOPHERD_PIDFILE="/var/run/gopherd.pid"

# TODO . /gopher.rc
g_errx () {
	echo "${1:-'no msg'}" 1>&2;
}

g_err () {
	if [ -z "$1" ]; then
		echo 'Fatal error! too few arguments to g_err' 1>&2;
		exit 10;
	fi
	echo "${2:-'no msg'}" 1>&2;
	exit "${1}";
}

g_stop_cmd () {
	stptout=${1:-15}
	pid="`head -1 ${GOPHERD_PIDFILE} 2>&-`" ;
	timout=0;

	if ! kill "${pid}" 2>&-; then
		g_errx "Killing ${pid:-'no pid'} failure!";
		return 1;
	fi
	while ! kill -0 "${pid}" 2>&- && [ $timout -le "$stptout" ];
	do
		echo -n ".";
		: $((timout++));
		sleep 1;
	done
	return 0;
}

g_check_running () {
	pid="`head -1 ${GOPHERD_PIDFILE} 2>&-`" ;
	
	if [ ! -f "${GOPHERD_PIDFILE}" ]; then
		return 1;
	fi
	if [ "${pid:-0}" -gt 1 ] && kill -0 ${pid} 2>&-; then
		return 0;
	fi
	# stale pidfile
	g_errx "Removing a stale pidfile";
	rm -- "${GOPHERD_PIDFILE}"
	return 1;
}

g_status () {
	if g_check_running; then
		g_errx "gopherd is running";
	else
		g_errx "gopherd is not running";
	fi
}

g_fw_reload () {
	if ! g_check_running; then
		g_errx "gopherd is not running";
		return 1;
	fi	
	echo "Reloading gfw";
	if ! kill -USR1 "`head -1 ${GOPHERD_PIDFILE}`" 2>&-; then
		g_errx "Couldn't reload gfw";
		return 1;
	fi
	return 0;
}

usage () {
	g_err 64 "usage: gopherd.sh [start|stop|gfwreload]";
}

########################################################################
# main
########################################################################

for CMD in $@;
do
	[ -z "$CMD" ] && usage;
	case "$CMD" in
		start)
			g_check_running && g_err 3 "gopherd is already running";
			echo "Starting gopherd" 2>&1;
			${GOPHERD:-/usr/local/sbin/gopherd} ${GOPHERD_FLAGS:-""}
		;;
		stop)
			g_check_running || g_err 3 "gopherd is not running";
			echo "Stopping gopherd" 2>&1;
			g_stop_cmd || g_err 3 "Couldn't stop gopherd";
		;;
		status)
			g_status;
		;;
		sleep)
			sleep 1 || g_err 3 "Sleep interrupted";
		;;
		gfwreload)
			g_fw_reload || g_err 3 "Failed to reload gfw";
		;;
		*)
			usage;
		;;
	esac
done
